package cn.jolyoulu.common.core.ddd.event.impl;

import cn.jolyoulu.common.core.ddd.event.DomainEvent;
import cn.jolyoulu.common.core.ddd.event.EventHandler;
import cn.jolyoulu.common.core.ddd.event.EventStrategy;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: JolyouLu
 * @Date: 2025/1/20 11:19
 * @Version 1.0
 */
@Slf4j
@Service
public class SimpleEventStrategyImpl implements EventStrategy, BeanPostProcessor {

    /**
     * 事件Map
     */
    private final static Map<Class<? extends DomainEvent>, EventHandler> eventMap = new HashMap<>();

    /**
     * 自动添加EventHandler
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof EventHandler && bean instanceof DomainEvent) {
            eventMap.put((Class<? extends DomainEvent>) bean.getClass(), (EventHandler) bean);
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    /**
     * 添加处理器
     * @param eventClass
     * @param handler
     * @param <T>
     */
    public <T extends DomainEvent> void addHandler(Class<T> eventClass,EventHandler handler){
        eventMap.put(eventClass,handler);
    }

    /**
     * 事件处理
     * @param event
     * @param tClass
     * @param <T>
     */
    public <T extends DomainEvent> void invoke(Class<T> tClass,T event){
        EventHandler<T> eventHandler = eventMap.get(tClass);
        if (Objects.isNull(eventHandler)){
            log.error("事件handler {} 未找到",tClass);
        }
        eventHandler.handler(event);
    }
}
